// 将数据以文件形式保存
import {app} from "electron";
import path from "path";
import * as fs from "node:fs";

//创建目录，测试中的表现：使用递归创建（允许多级目录），否则必须逐级创建
export function checkFolder(folderPath) {
	if (!fs.existsSync(folderPath)) {
		fs.mkdirSync(folderPath, {recursive: true});
	}
}

const basePath = process.env.NODE_ENV === 'production' ? app.getPath('userData') : __dirname;
let folderPath = path.join(basePath, "datas/files/");

export function createLocalFile(fileName: string, data: any) {
	checkFolder(folderPath);
	// 确定文件路径
	const filePath = path.join(folderPath, fileName);

	// 使用fs.writeFile (异步）创建文件，如果文件已存在则会被覆盖
	return fs.promises
		.writeFile(filePath, data, {flag: "w"})
		.then(() => {
			console.log(`文件已创建成功：${filePath}`);
			return true;
		})
		.catch((err) => {
			console.log(err);
			return false;
		});
}

export function loadLocalFile(fileName: string) {
	const filePath = path.join(folderPath, fileName);
	return fs.readFileSync(filePath, "utf8");
}
